#!/usr/bin/python3
# -*- coding: utf-8 -*-

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager

from utils.logger import Logger
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.edge.service import Service as EdgeService
logger = Logger(logger="BrowserDriver").getlog()

class BrowserDriver:
    driver = None
    def __init__(self):
        if BrowserDriver.driver is None:
            BrowserDriver.driver = self.openbrowser()

    def openbrowser(self,browserName = "Firefox"):
        logger.info("选择的浏览器为: %s 浏览器" % browserName)
        if browserName == "Firefox":
            driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()))
            logger.info("启动火狐浏览器")
        elif browserName == "edge":
            driver = webdriver.Edge(service=EdgeService(EdgeChromiumDriverManager().install()))
            logger.info("启动Edge浏览器")
        else:
            chrome_options = Options()
            chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
            chrome_options.add_argument('--start-maximized')  # 指定浏览器分辨率
            chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
            chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
            chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面.
            chrome_options.add_argument('--disable-extensions')
            chrome_options.add_argument('lang=zh_CN.UTF-8')
            driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()),options=chrome_options)

            logger.info("启动谷歌浏览器")

        driver.implicitly_wait(5)
        logger.info("设置5秒隐式等待时间")
        return driver

    def quit_browser(self):
        logger.info("关闭浏览器")
        self.driver.quit()

